package com.ruibang.glass.iso.service.impl.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.Constants;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.common.domain.GlobalUser;
import com.ruibang.glass.common.domain.camunda.BpmProcessInstanceCreate;
import com.ruibang.glass.common.domain.camunda.BpmProcessInstanceStatus;
import com.ruibang.glass.common.domain.camunda.BpmTaskApproveReq;
import com.ruibang.glass.common.domain.file.FileBusiness;
import com.ruibang.glass.iso.constant.IsoErrorCode;
import com.ruibang.glass.iso.domain.req.TargetIndicatorsReq;
import com.ruibang.glass.iso.entity.TargetIndicators;
import com.ruibang.glass.iso.feign.CamundaApi;
import com.ruibang.glass.iso.feign.FileApi;
import com.ruibang.glass.iso.mapper.TargetIndicatorsMapper;
import com.ruibang.glass.iso.service.impl.TargetIndicatorsService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.common.exception.ServiceException;
import com.teaming.cloud.framework2.common.model.ResultBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: songJinKang
 * @CreateTime: 2024-06-18  20:24
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Service
public class TargetIndicatorsServiceImpl extends ServiceImpl<TargetIndicatorsMapper, TargetIndicators> implements TargetIndicatorsService {

    @Autowired
    private FileApi fileApi;

    @Autowired
    private CommonService commonService;

    @Autowired
    private CamundaApi camundaApi;

    @Autowired
    private RedisSingleService redisService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveInfo(TargetIndicators targetIndicators) {
        //保存
        this.save(targetIndicators);
        //保存文件
        FileBusiness fileBusiness = new FileBusiness();
        fileBusiness.setFileIds(targetIndicators.getFileIds());
        fileBusiness.setBusinessId(targetIndicators.getId());
        fileApi.updateBusinessById(fileBusiness);
    }

    @Override
    public IPage<TargetIndicators> pageQuery(TargetIndicatorsReq targetIndicatorsReq) {
        QueryWrapper<TargetIndicators> qw = new QueryWrapper<>();
        qw.lambda().orderByDesc(TargetIndicators::getCreateTime);
        Page<TargetIndicators> page = this.page(new Page<>(targetIndicatorsReq.getPageNo(), targetIndicatorsReq.getPageSize()), qw);
        if (page != null && CollectionUtils.isNotEmpty(page.getRecords())) {
            List<TargetIndicators> targetIndicatorsList = page.getRecords();
            List<String> ids = targetIndicatorsList.stream().map(TargetIndicators::getId).collect(Collectors.toList());
            ResultBody<List<FileBusiness>> resultBody = fileApi.getFileBusinessByIds(ids);
            //文件数据
            if (resultBody != null && CollectionUtils.isNotEmpty(resultBody.getData())) {
                List<FileBusiness> fileBusinesses = resultBody.getData();
                Map<String, List<String>> filMap = fileBusinesses.stream().collect(Collectors.toMap(FileBusiness::getBusinessId, FileBusiness::getFileIds));
                for (TargetIndicators targetIndicator : targetIndicatorsList) {
                    targetIndicator.setFileIds(filMap.get(targetIndicator.getId()));
                }
            }
            //流程信息
            ResultBody<List<BpmProcessInstanceStatus>> bpmResultBody = camundaApi.queryProcessInstanceStatus(ids);
            if (bpmResultBody != null && CollectionUtils.isNotEmpty(bpmResultBody.getData())) {
                List<BpmProcessInstanceStatus> bpmProcessInstanceStatusList = bpmResultBody.getData();
                Map<String, BpmProcessInstanceStatus> bpmProcessInstanceStatusMap = bpmProcessInstanceStatusList.stream().collect(Collectors.toMap(BpmProcessInstanceStatus::getBusinessKey, e -> e, (oldEl, newEl) -> newEl));
                for (TargetIndicators targetIndicators : targetIndicatorsList) {
                    BpmProcessInstanceStatus bpmProcessInstanceStatus = bpmProcessInstanceStatusMap.get(targetIndicators.getId());
                    if (bpmProcessInstanceStatus != null) {
                        String userId = bpmProcessInstanceStatus.getUserId();
                        if (StringUtils.isNotBlank(userId)) {
                            Object userNameObj = redisService.hget(RedisKey.USER_GROUP_TYPE, userId);
                            if (userNameObj != null) {
                                targetIndicators.setCurrentAuditBy(userNameObj.toString());
                            }
                            targetIndicators.setApproveUserId(userId);
                        }
                        targetIndicators.setProcessInstanceId(bpmProcessInstanceStatus.getProcessInstanceId());
                        targetIndicators.setNodeKey(bpmProcessInstanceStatus.getNodeKey());
                        targetIndicators.setNodeName(bpmProcessInstanceStatus.getNodeName());
                    }
                }
            }
        }
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(TargetIndicators targetIndicators) {
        //更新
        this.updateById(targetIndicators);
        //保存文件
        FileBusiness fileBusiness = new FileBusiness();
        fileBusiness.setFileIds(targetIndicators.getFileIds());
        fileBusiness.setBusinessId(targetIndicators.getId());
        fileApi.updateBusinessById(fileBusiness);
    }

    @Override
    public void startProcess(BpmProcessInstanceCreate bpmProcessInstanceCreate) {
        TargetIndicators targetIndicators = this.getById(bpmProcessInstanceCreate.getBusinessKey());
        //发起流程
        GlobalUser user = commonService.getUser();
        if (user == null) {
            throw new ServiceException(IsoErrorCode.GET_CURRENT_USER_FAIL.getCode(), IsoErrorCode.GET_CURRENT_USER_FAIL.getMsg());
        }
        Map<String, Object> variables = new HashMap<>(16);
        variables.put(Constants.PROCESS_INSTANCE_STARTER_USER_ID, user.getUserId());
        variables.put(Constants.PROCESS_INSTANCE_BUSINESS_KEY, targetIndicators.getId());
        variables.put(Constants.PROCESS_INSTANCE_MENU_ID, targetIndicators.getMenuId());
        bpmProcessInstanceCreate.setVariables(variables);
        bpmProcessInstanceCreate.setBusinessKey(targetIndicators.getId());
        bpmProcessInstanceCreate.setMenuId(targetIndicators.getMenuId());
        String processId = commonService.startProcess(bpmProcessInstanceCreate);
        //直接通过第一流程节点
        if (StringUtils.isNotBlank(processId)) {
            BpmTaskApproveReq bpmTaskApproveReq = new BpmTaskApproveReq();
            bpmTaskApproveReq.setId(processId);
            bpmTaskApproveReq.setUserId(user.getUserId());
            camundaApi.approve(bpmTaskApproveReq);
        }
    }

}
